const express = require("express");
const cookieParser = require("cookie-parser");
const logger = require("morgan");
const cors = require("cors");
const { expressjwt } = require("express-jwt");
const { jwtConfig, filePath } = require("./config/application.config");
const { wrapperRoutes } = require("./routes");

const app = express();

// 全局中间件 挂载提示函数/成功函数
app.use((req, res, next) => {
  // -1 失败 0 成功 401 身份验证失败
  res.err = (errMsg, code = -1) => {
    if (code === 401) {
      res.status(401);
    }
    res.send({
      code,
      message: errMsg instanceof Error ? errMsg.message : errMsg,
    });
  };
  res.page = (count = 0, rows = [], msg = "查询成功") => {
    res.send({
      code: 0,
      message: msg,
      data: {
        list: rows ?? [],
        total: count ?? 0,
      },
    });
  };
  res.cc = (data, msg = "操作成功") => {
    res.send({
      code: 0,
      message: msg,
      data,
    });
  };
  next();
});
app.use(cors());
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use("/file_assets", express.static(filePath));

// jwt校验白名单
app.use(
  expressjwt({ secret: jwtConfig.jwtSecretKey, algorithms: ["HS256"] }).unless({
    path: [/^\/login\//, /^\/file_assets\//],
  })
);

// 挂载路由
wrapperRoutes(app);

// 全局错误处理
app.use(function (err, req, res, next) {
  switch (err.name) {
    case "UnauthorizedError":
      res.err("身份认证失败,请先登录", 401);
      break;
    case "SequelizeValidationError":
    case "SequelizeUniqueConstraintError":
      const msg = err.errors.map((item) => item.message).join(","); // 错误信息全量返回
      res.err(msg);
      break;
    default:
      res.err(err);
      break;
  }
});

module.exports = app;
